package fhp.hlhj.giantfold.activity.camera
import android.Manifest
import android.annotation.TargetApi
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.ImageFormat
import android.hardware.camera2.*
import android.media.Image
import android.media.ImageReader
import android.net.Uri
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.support.annotation.RequiresApi
import android.support.v4.app.ActivityCompat
import android.util.Log
import android.util.SparseIntArray
import android.view.Surface
import android.view.SurfaceHolder
import android.view.View
import android.widget.Toast
import com.bumptech.glide.Glide
import com.lzy.okgo.model.HttpParams
import fhp.hlhj.giantfold.BaseActivity
import fhp.hlhj.giantfold.Contents
import fhp.hlhj.giantfold.R
import fhp.hlhj.giantfold.activity.camera.CircleCameraInterface.getCircleBitmap
import fhp.hlhj.giantfold.event.CapImgEvent
import fhp.hlhj.giantfold.interfaces.ISendImg
import fhp.hlhj.giantfold.javaBean.BaseBean
import fhp.hlhj.giantfold.presenter.SendImgPresenter
import fhp.hlhj.giantfold.utils.MyUtils
import kotlinx.android.synthetic.main.activity_camera2_aty.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import java.nio.ByteBuffer
import java.util.*
class Camera2Aty : BaseActivity(), SurfaceHolder.Callback, ISendImg {
    override fun senImgResp(baseBean: BaseBean) {
        if (baseBean.code==200){
            MyUtils.toast("上传成功")
        }else{
            MyUtils.toast(baseBean.msg)
        }
        finish()
    }

    private lateinit var sendImgPresenter:SendImgPresenter
    private lateinit var childHandler:Handler
    private lateinit var mainHandler:Handler
    private lateinit var mCameraID:String
    private lateinit var mImageReader:ImageReader
    private var mCameraCaptureSession: CameraCaptureSession? = null
    private var mCameraManager: CameraManager? = null//摄像头管理器
    private var mCameraDevice: CameraDevice? = null
    private val TAG="info"
    companion object {
        private val ORIENTATIONS = SparseIntArray()
        ///为了使照片竖直显示
        init {
            ORIENTATIONS.append(Surface.ROTATION_0, 90)
            ORIENTATIONS.append(Surface.ROTATION_90, 0)
            ORIENTATIONS.append(Surface.ROTATION_180, 270)
            ORIENTATIONS.append(Surface.ROTATION_270, 180)
        }
    }
    /**
     * SurfaceView的Surface监听
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    override fun surfaceDestroyed(holder: SurfaceHolder?) {
        // 释放Camera资源
        if (null != mCameraDevice) {
            mCameraDevice!!.close();
            this.mCameraDevice = null;
        }
    }
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun surfaceCreated(holder: SurfaceHolder?) {
        initCamera()
    }
    override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {
    }
    override fun getContentId(): Int = R.layout.activity_camera2_aty
    override fun initView() {
        surfaceview.holder.addCallback(this)
        sendImgPresenter= SendImgPresenter(this)
    }
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    override fun initListener() {
        btTakePhoto.setOnClickListener {
            takePicture()
        }
    }
    /**
     * 使能摄像头
     */
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    @TargetApi(Build.VERSION_CODES.KITKAT)
    private fun initCamera() {
        val handlerThread =HandlerThread("Camera2")
        handlerThread.start()
        childHandler =  Handler(handlerThread.looper)
        mainHandler =  Handler(mainLooper)
        mCameraID = "" + CameraCharacteristics.LENS_FACING_FRONT//后摄像头
        mImageReader = ImageReader.newInstance(1080, 1920, ImageFormat.JPEG,1)
        mImageReader.setOnImageAvailableListener(object :ImageReader.OnImageAvailableListener {
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            override fun onImageAvailable(reader: ImageReader?) {
                mCameraDevice?.close()
                surfaceview.visibility = View.GONE
//                iv_show.setVisibility(View.VISIBLE);
                // 拿到拍照照片数据
                val image = reader?.acquireNextImage()
                val buffer = image!!.planes[0].buffer
                val bytes = ByteArray(buffer.remaining())
                buffer.get(bytes)//由缓冲区存入字节数组
                val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
                if (bitmap != null) {
                    cutBitMap(bitmap)
                }
            } //可以在这里处理拍照得到的临时照片 例如，写入本地
        }, mainHandler)
        //获取摄像头管理
        mCameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
        try {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                return
            }
            //打开摄像头
            mCameraManager!!.openCamera(mCameraID, stateCallback, mainHandler)
        } catch ( e: CameraAccessException) {
            e.printStackTrace()
        }
    }
    /**
     * 摄像头监听
     */
    private val stateCallback = object : CameraDevice.StateCallback() {
        @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
        override fun onOpened(camera: CameraDevice) {//打开摄像头
            mCameraDevice = camera
            //开启预览
            takePreview()
        }
        @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
        override fun onDisconnected(camera: CameraDevice) {//关闭摄像头
            if (null != mCameraDevice) {
                mCameraDevice!!.close()
                this@Camera2Aty.mCameraDevice = null
            }
        }
        override fun onError(camera: CameraDevice, error: Int) {//发生错误
            Toast.makeText(this@Camera2Aty, "摄像头开启失败", Toast.LENGTH_SHORT).show()
        }
    }
    /**
     * 拍照
     */
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    @TargetApi(Build.VERSION_CODES.KITKAT)
    private fun takePreview() = try {
        // 创建预览需要的CaptureRequest.Builder
        val previewRequestBuilder = mCameraDevice!!.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
        // 将SurfaceView的surface作为CaptureRequest.Builder的目标
        previewRequestBuilder.addTarget(surfaceview.holder.surface)
        // 创建CameraCaptureSession，该对象负责管理处理预览请求和拍照请求
        mCameraDevice!!.createCaptureSession(Arrays.asList(surfaceview.holder.surface, mImageReader.surface), object : CameraCaptureSession.StateCallback() // ③
        {
            override fun onConfigured(cameraCaptureSession: CameraCaptureSession) {
                if (null == mCameraDevice) return
                // 当摄像头已经准备好时，开始显示预览
                mCameraCaptureSession = cameraCaptureSession
                try {
                    // 自动对焦
                    previewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE)
                    // 打开闪光灯
                    previewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH)
                    // 显示预览
                    val previewRequest = previewRequestBuilder.build()
                    mCameraCaptureSession!!.setRepeatingRequest(previewRequest, null, childHandler)
                } catch (e: CameraAccessException) {
                    e.printStackTrace()
                }
            }
            override fun onConfigureFailed(cameraCaptureSession: CameraCaptureSession) {
                Toast.makeText(this@Camera2Aty, "配置失败", Toast.LENGTH_SHORT).show()
            }
        }, childHandler)
    } catch (e: CameraAccessException) {
        e.printStackTrace()
    }

    /**
     * 拍照
     */
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    private fun takePicture() {
        if (mCameraDevice == null){

        }else{
            // 创建拍照需要的CaptureRequest.Builder
            val captureRequestBuilder: CaptureRequest.Builder
            try {
                captureRequestBuilder = mCameraDevice!!.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE)
                // 将imageReader的surface作为CaptureRequest.Builder的目标
                captureRequestBuilder.addTarget(mImageReader.getSurface())
                // 自动对焦
                captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE)
                // 自动曝光
                captureRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH)
                // 获取手机方向
                val rotation = getWindowManager().getDefaultDisplay().getRotation()
                // 根据设备方向计算设置照片的方向
                captureRequestBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation))
                //拍照
                val mCaptureRequest = captureRequestBuilder.build()
                mCameraCaptureSession!!.capture(mCaptureRequest, null, childHandler)
            } catch (e: CameraAccessException) {
                e.printStackTrace()
            }
        }
    }
    private fun cutBitMap(b: Bitmap){
        //保存图片到sdcard
        if (b != null) {
            //设置FOCUS_MODE_CONTINUOUS_VIDEO 之后，myParam.set("rotation",90);失效
            //图片不能旋转，在这里旋转
            val rotaBitmap = ImageUtil.getRotateBitmap(b, 0f)
            Log.i(TAG, "长度") // 1080
            var DST_RECT_WIDTH= toCInt(resources.displayMetrics.widthPixels*0.8)
            var DST_RECT_HEIGHT=toCInt(resources.displayMetrics.heightPixels*0.73)
            val x0 = toCInt(getResources().getDisplayMetrics().widthPixels * 0.1)
            val y0 = toCInt(getResources().getDisplayMetrics().heightPixels * 0.07)
            Log.i(TAG, " rotaBitmap.getWidth() = " + rotaBitmap.width) // 1080
            Log.i(TAG, "rotaBitmap.getHeight() = " + rotaBitmap.height) //1920
            Log.i(TAG, "自己的长度---------$x0,$y0,$DST_RECT_WIDTH,$DST_RECT_HEIGHT") //1920
//            val rectBitmap = Bitmap.createBitmap(rotaBitmap, x0, y0, DST_RECT_WIDTH, DST_RECT_HEIGHT)//得到它的正方型 or 矩形的图片
            val rectBitmap = Bitmap.createBitmap(rotaBitmap, toCInt(rotaBitmap.width*0.1), toCInt(rotaBitmap.height*0.07), toCInt(rotaBitmap.width*0.8), toCInt(rotaBitmap.height*0.73))//得到它的正方型 or 矩形的图片
            //source:要从中截图的原始位图   int x:起始x坐标    int y:起始y坐标    int width:要截图的宽度      int height:要截图的高度
            Log.i(TAG, "DST_RECT_WIDTH " + DST_RECT_WIDTH + DST_RECT_HEIGHT + "yyyyyyyyyyyyyyyyyyyyyyy")
            val circle = getCircleBitmap(rectBitmap)
            FileUtil.saveBitmap(rectBitmap)
            val thumbPath = FileUtil.getJpegName()
            val file = File(thumbPath!!)
            val uri = Uri.fromFile(file)
            Log.d(TAG, "===============================================================" + thumbPath)
            if (thumbPath != null) {
                EventBus.getDefault().postSticky(CapImgEvent(thumbPath))
            }
        }
    }
    fun toCInt(double: Double) :Int{
        val str = double.toString()
        val list = str.split(".")
        return Integer.parseInt(list[0])
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    fun handImg(event:CapImgEvent){
        if (event.path != null) {
            val file = File(event.path)
            val uri = Uri.fromFile(file)
            val intent1 = Intent(this@Camera2Aty, ImageCapterActivity::class.java)
            intent1.data = uri
            intent1.putExtra("thumbPath", event.path)
            startActivityForResult(intent1, 1)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode!= Activity.RESULT_OK)return
        if (requestCode==1){
            val path = data?.getStringExtra("thumbPath")
            val params = HttpParams()
            if (path!=null){
                params.put("user_id",Contents.userId)
                params.put("merchant_id",intent.getStringExtra("mid"))
                params.put("receipts", File(path))
                sendImgPresenter.sendImg(params)
            }
        }
    }
}
